<!-- 富文本组件 -->
<template>
  <div>
    <vue-editor v-if="group.hasOwnProperty('subjectTxt')" ref="question-editor" :editor-toolbar="customToolbar" v-model="group.subjectTxt" :disabled="disabledEditor" use-custom-image-handler @imageAdded="handleQuestionImageAdded" @text-change="handleTextChange">
      <div slot="toolbar" class="my-toolbar" v-if="showAudioTool">
        <!--<span class="file-audio" @click="handleClickFileAudio($event, 'question-editor')">-->
          <!--<span :style="{backgroundImage: `url(${fileAudio})`}"></span>-->
          <!--<span :style="{backgroundImage: `url(${fileAudioHover})`}"/>-->
          <!--<input type="file" accept=".m4a,.mp3,.wav" @change="handleFileAudioChange($event, 'question-editor')">-->
        <!--</span>-->
        <!--<span v-if="group.category === 'blank'" class="edit-audio" @click="handleClickEdit($event, 'question-editor')">-->
          <!--<span :style="{backgroundImage: `url(${editPng})`}"/>-->
          <!--<span :style="{backgroundImage: `url(${editHoverPng})`}"/>-->
        <!--</span>-->
        <div class="file-audio" @click="handleClickFileAudio($event, 'question-editor')">
          <div :style="{backgroundImage: `url(${fileAudio})`}">
            <span>添加音频</span>
          </div>
          <div :style="{backgroundImage: `url(${fileAudioHover})`}">
            <span style="color: #409eff">添加音频</span>
          </div>
          <input type="file" accept=".m4a,.mp3,.wav" @change="handleFileAudioChange($event, 'question-editor')">
        </div>
        <div v-if="group.category === 'blank'" class="file-audio" @click="handleClickEdit($event, 'question-editor')">
          <div :style="{backgroundImage: `url(${editPng})`}">
            <span>填写答案</span>
          </div>
          <div :style="{backgroundImage: `url(${editHoverPng})`}">
            <span style="color: #409eff">填写答案</span>
          </div>
        </div>
      </div>
    </vue-editor>
    <vue-editor v-else-if="group.hasOwnProperty('optionTxt')" ref="analytic-editor" :editor-toolbar="customToolbar" v-model="group.optionTxt" :disabled="disabledEditor" use-custom-image-handler @imageAdded="handleQuestionImageAdded">
      <div slot="toolbar" class="my-toolbar">
        <div class="file-audio" @click="handleClickFileAudio($event, 'analytic-editor')" v-if="showAudioTool">
          <div :style="{backgroundImage: `url(${fileAudio})`}">
            <span>添加音频</span>
          </div>
          <div :style="{backgroundImage: `url(${fileAudioHover})`}">
            <span style="color: #409eff">添加音频</span>
          </div>
          <input type="file" accept=".m4a,.mp3,.wav" @change="handleFileAudioChange($event, 'analytic-editor')">
        </div>
      </div>
    </vue-editor>
  </div>
</template>

<script>
import fileAudio from '@/assets/svg/file-audio.svg'
import fileAudioHover from '@/assets/svg/file-audio_hover.svg'
import editPng from '@/assets/svg/edit.svg'
import editHoverPng from '@/assets/svg/edit_hover.svg'
import audioPng from '@/assets/logo_images/audio.png'
import { uploadImageFile, uploadAudioFile, uploadAudioToOss, uploadImageToOss } from '@/api/question'
import { getOss } from '@/api/login'
export default {
  name: 'RichText',
  props: {
    group: Object,
    showAudioTool: {
      type: Boolean,
      default: true
    },
    disabledEditor: {
      type: Boolean,
      default: false
    },
    customToolbar: {
      type: Array,
      default: function () {
        return ['bold', 'italic', 'underline', 'image']
      }
    }
  },
  data() {
    return {
      fileAudio,
      fileAudioHover,
      editPng,
      editHoverPng,
      // customToolbar: ['bold', 'italic', 'underline', 'image'],
      ossClient: null,
      ossParams: null
    }
  },
  created() {
    const _this = this
    _this.getOssData()
  },
  mounted() {
    this.addToolBarText()
  },
  methods: {
    getOssData() {
      const _this = this
      getOss().then(res => {
        _this.ossParams = res
      })
    },
    // 图片工具栏添加文字
    addToolBarText() {
      this.$nextTick(function(){
        const toolbarDom = document.getElementsByClassName('ql-image')
        if (toolbarDom.length > 0) {
          for (let i = 0; i < toolbarDom.length; i++) {
            const domItem = toolbarDom[i]
            const spanHasDom = domItem.getElementsByTagName('span');
            if (spanHasDom.length === 0) {
              var spanDom = document.createElement("span")
              spanDom.innerText = '添加图片'
              domItem.appendChild(spanDom)
            }
          }
        }
      })
    },
    // 点击音频
    handleClickFileAudio(e, name) {
      if (name === 'question-editor' && this.group.subjectAudio) {
        this.$message({
          message: '已上传音频',
          type: 'warning'
        })
        return
      }
      if (name === 'analytic-editor' && this.group.optionAudio) {
        this.$message({
          message: '已上传音频',
          type: 'warning'
        })
        return
      }
      const ref = this.$refs[name]
      if (Array.isArray(ref)) {
        ref[0].quill.focus()
      } else {
        ref.quill.focus()
      }
      e.currentTarget.querySelector('input').click()
    },
    // 上传图片
    async handleQuestionImageAdded(file, Editor, cursorLocation, resetUploader) {
      const formData = new FormData()
      /*formData.append('image', file)
      const { url } = await uploadImageFile(formData)
      Editor.insertEmbed(cursorLocation, 'image', url)
      Editor.setSelection(cursorLocation + 1)
      resetUploader()
      return url*/

      const _this = this
      const loading = _this.$loading({
        lock: true,
        text: '音频上传中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.6)'
      })
      formData.append('name', file.name)
      formData.append('key', _this.ossParams.dir + file.name)
      formData.append('OSSAccessKeyId', _this.ossParams.accessid)
      formData.append('success_action_status', '200')
      formData.append('signature', _this.ossParams.signature)
      formData.append('policy', _this.ossParams.policy)
      formData.append('file', file)
      uploadImageToOss(_this.ossParams.host, formData).then(res => {
        loading.close()
        const path = _this.ossParams.host + '/' + _this.ossParams.dir + file.name
        Editor.insertEmbed(cursorLocation, 'image', path)
        Editor.setSelection(cursorLocation + 1)
        resetUploader()
      }).catch(err => {
        loading.close()
        console.info(err)
      })
    },
    // 监听编辑器文本变化
    handleTextChange() {
      const Editor = (Array.isArray(this.$refs['question-editor']) ? this.$refs['question-editor'][0] : this.$refs['question-editor']).quill
      const text = Editor.getText()
      this.$emit('textInsertCallback', text)
      const editorContents = Editor.getContents()
      let isUploadAudio = false
      if (editorContents.ops) {
        const opsArray = editorContents.ops
        for (let i = 0; i < opsArray.length; i++) {
          if (opsArray[i].insert.image) {
            if (opsArray[i].insert.image.indexOf('static/img/audio') > -1) {
              isUploadAudio = true
              break
            }
          }
        }
      }
      if (!isUploadAudio) {
        if (this.group.hasOwnProperty('subjectTxt')) {
          this.group.subjectAudio = ''
        } else if (this.group.hasOwnProperty('optionTxt')) {
          this.group.optionAudio = ''
        }
      }
      console.info(Editor.getContents())
    },
    // 上传音频
    async handleFileAudioChange(e, name, index) {
      const _this = this
      const file = e.target.files[0]
      const Editor = (Array.isArray(this.$refs[name]) ? this.$refs[name][0] : this.$refs[name]).quill
      const range = Editor.getSelection()
      const cursorLocation = range.index
      const formData = new FormData()
      // formData.append("audio", file)
      const loading = _this.$loading({
        lock: true,
        text: '音频上传中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.6)'
      })
      formData.append('name', file.name)
      formData.append('key', _this.ossParams.dir + file.name)
      formData.append('OSSAccessKeyId', _this.ossParams.accessid)
      formData.append('success_action_status', '200')
      formData.append('signature', _this.ossParams.signature)
      formData.append('policy', _this.ossParams.policy)
      formData.append('file', file)
      uploadAudioToOss(_this.ossParams.host, formData).then(res => {
        loading.close()
        const path = _this.ossParams.dir + file.name
        if (name === 'question-editor') {
          _this.group.subjectAudio = path
        } else if (name === 'analytic-editor') {
          this.group.optionAudio = path
        }
        Editor.insertEmbed(cursorLocation, 'image', audioPng)
        Editor.setSelection(cursorLocation + 1)
        e.target.value = ''
      }).catch(err => {
        loading.close()
        console.info(err)
      })
      // uploadAudioFile(formData).then(res => {
      //   if (res) {
      //     loading.close()
      //     const path = res.url
      //     if (name === 'question-editor') {
      //       _this.group.subjectAudio = path
      //     } else if (name === 'analytic-editor') {
      //       this.group.optionAudio = path
      //     }
      //     // Editor.insertEmbed(cursorLocation, "image", audioSvg)
      //     Editor.insertEmbed(cursorLocation, "image", audioPng)
      //     Editor.setSelection(cursorLocation + 1)
      //     // Editor.insertEmbed(cursorLocation, `<audio src="${path}"></audio>`)
      //     // _this.$forceUpdate()
      //     // Editor.insertEmbed(cursorLocation, "audio", path)
      //     e.target.value = ''
      //   }
      // }).catch(err => {
      //   loading.close()
      //   console.info(err)
      // })
    },
    // 填空题目填写答案
    handleClickEdit(e, name) {
      const _this = this
      _this.$prompt('请输入答案', '提示', {
        inputValue: '',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: '',
        inputErrorMessage: ''
      }).then(({ value }) => {
        const Editor = (Array.isArray(_this.$refs[name]) ? _this.$refs[name][0] : _this.$refs[name]).quill
        if (Array.isArray(Editor)) {
          Editor.focus()
        } else {
          Editor.focus()
        }
        const range = Editor.getSelection()
        const cursorLocation = range.index
        Editor.insertText(cursorLocation, '[[' + value + ']]', '', true)
      })
    }
  }
}
</script>

<style lang="less" scoped>
  /deep/ .ql-editor img {
    height: 130px !important;
  }
</style>
